﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BoardScript : MonoBehaviour
{
    public Player Player1;
    public Player Player2;
    public Rigidbody2D BoardRigidBody;
    public BoxCollider2D BoardBoxCollider;
    public SpriteRenderer BoardSprite;
    public GameObject LeftBoard;
    public GameObject LeftBoardShort;
    public GameObject RightBoard;
    public GameObject RightBoardShort;

    private const float BoardEdge = 0.6f;
    private const float BreakLength = 8f;
    private const float StartBreakLength = 4.5f;
    private const float DropTextInterval = 1f;

    private float mLastDropTextTime;
    private void Update()
    {
        Vector2 size = BoardBoxCollider.size;
        size.x = Vector2.Distance(Player1.transform.position, Player2.transform.position) + BoardEdge * 2f;
        BoardBoxCollider.size = size;

        size = BoardSprite.size;
        size.x = Vector2.Distance(Player1.transform.position, Player2.transform.position) + BoardEdge * 2f;
        BoardSprite.size = size;

        Vector3 player1Head = Player1.GetHeadPosition();
        Vector3 player2Head = Player2.GetHeadPosition();
        Vector3 center = (player1Head + player2Head) / 2f;
        transform.position = center;
        transform.right = player2Head - player1Head;
        LeftBoard.transform.localPosition = Vector3.left * size.x / 2f;
        LeftBoardShort.transform.localPosition = Vector3.left * size.x / 2f;
        RightBoard.transform.localPosition = Vector3.right * size.x / 2f;
        RightBoardShort.transform.localPosition = Vector3.right * size.x / 2f;

        float breakPercent = (BoardSprite.size.x - StartBreakLength) / (BreakLength / StartBreakLength);
        if (breakPercent > 0)
        {
            BoardSprite.color = Color.Lerp(Color.white, Color.red, Mathf.Clamp01(breakPercent));
            if (breakPercent >= 1f)
            {
                TryDropText();
            }
        }
    }
    public void TryDropText()
    {
        if (Time.time - mLastDropTextTime >= DropTextInterval)
        {
            mLastDropTextTime = Time.time;
            TextScript text = GameManager.GetInstance().GetRandomText();

            if (text != null)
                text.gameObject.layer = PhysicsLayer.DroppedText;
        }
    }
    public void SetColliderShort(bool isShort)
    {
        LeftBoard.SetActive(!isShort);
        RightBoard.SetActive(!isShort);
        LeftBoardShort.SetActive(isShort);
        RightBoardShort.SetActive(isShort);
    }
}
